datapoints = [(-0.77, 6.79), (2.40, 12.45), (5.64, 18.60), (8.20, 26.36), (7.08, 21.44),
    (10.32, 28.51), (6.31, 22.29), (6.16, 16.24), (6.22, 14.75), (11.01, 31.76),
    (12.94, 28.38), (13.96, 34.59), (17.17, 43.10), (17.24, 43.65), (18.80, 39.69),
    (11.97, 28.47), (17.70, 39.41), (19.39, 45.04), (23.30, 56.29), (16.03, 38.22),
    (23.81, 55.02), (20.28, 45.16), (27.17, 58.36), (19.66, 44.74), (20.76, 41.92),
    (25.61, 60.81), (28.02, 56.96), (23.73, 48.90), (29.22, 60.88), (30.96, 71.13),
    (34.69, 77.62), (29.33, 63.12), (32.33, 72.50), (36.27, 73.89), (31.75, 68.06),
    (31.68, 67.70), (35.33, 76.57), (39.99, 81.28), (38.99, 81.61), (43.95, 96.36),
    (43.27, 95.94), (42.76, 93.84), (47.91, 103.26), (45.16, 99.70), (45.16, 90.49),
    (43.00, 87.88), (50.82, 107.50), (51.86, 104.63), (44.51, 95.35), (46.88, 96.14)
]

# 提取x,y
x_vals = [float(x) for x, y in data_points]
y_vals = [float(y) for x, y in data_points]

# 计算和
n = len(data_points)
sum_x = sum(x_vals)
sum_y = sum(y_vals)
sum_xy = sum(x * y for x, y in data_points)
sum_x_squared = sum(x ** 2 for x in x_vals)

# 使用公式计算斜率m和截距b
m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x ** 2)
b = (sum_y - m * sum_x) / n

print(f"线性回归方程为: y = {m:.2f}x + {b:.2f}")
import matplotlib.pyplot as plt
import numpy as np

# 创建回归方程的x和y值
x_fit = np.array(x_vals)
y_fit = m * x_fit + b

# 绘制数据点
plt.scatter(x_vals, y_vals, color='blue', label='数据点')

# 绘制回归直线
plt.plot(x_fit, y_fit, color='red', label=f'拟合直线: y = {m:.2f}x + {b:.2f}')

# 添加标题和标签
plt.title("线性回归拟合")
plt.xlabel("X 值")
plt.ylabel("Y 值")

# 显示图例
plt.legend()

# 显示图像
plt.show()
